package me.stephenj.contactsweb.service;

import me.stephenj.contactsweb.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Service
public class LoginService {

    private static final String SESSION_KEY = "sessionId";

    @Autowired
    LoginMapper loginMapper;

    public boolean checkLogin(String username, String password) {
        if (!password.equals(loginMapper.getPassword(username))) {
            return false;
        } else {
            return true;
        }
    }

    public String checkUser(String sessionId) {
        String username = loginMapper.getUsername(sessionId);
        if (username != null) {
            return username;
        } else {
            return null;
        }
    }

    public String createNewSessionId(HttpServletRequest request, String username) {
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY, username);
        loginMapper.updateSessionId(username, session.getId());
        session.setMaxInactiveInterval(36000);
        return session.getId();
    }

    public void createNewCookie(HttpServletResponse response, String sessionId) {
        Cookie cookie =  new Cookie(SESSION_KEY, sessionId);
        cookie.setMaxAge(36000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public void removeSessionId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        loginMapper.deleteSessionId(session.getId());
        session.removeAttribute(SESSION_KEY);
        session.invalidate();
    }

    public void cleanCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(SESSION_KEY, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public String getSessionId(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (SESSION_KEY.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
